package com.ebt.m.customer.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ebt.m.R;
import com.ebt.m.customer.CustomerUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.listener.IMultiSelectAdapter;
import com.ebt.m.customer.listener.IMultiSelectRecord;
import com.ebt.m.customer.ui.ActivityCustomerAll;
import com.ebt.m.customer.util.AttachmentUtil;
import com.ebt.m.customer.view.Dialog4CustomerAttachmentOperate;
import com.ebt.m.data.bean.EbtFile;
import com.ebt.m.data.entity.EntityCustomerAttachment;
import com.ebt.m.repository.provider.RepositoryProvider;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.utils.fileutils.FileSizeUtil;
import com.ebt.m.utils.fileutils.FileUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@SuppressLint("NewApi")
public class AdapterCustomerAttachment extends BaseAdapter implements IMultiSelectAdapter, View.OnClickListener {

    private Context mContext;
    private LayoutInflater inflater;
    private int mMaxMemory = 0;

    private List<EntityCustomerAttachment> attachments;

    private LruCache<String, Bitmap> mBitmapCache;

    private HashMap<Integer, Integer> sectionToPosition = new HashMap();

    private WeakReference<ListView> wrParent;

    private EbtFile mFile;

    public AdapterCustomerAttachment(Context context, List<EntityCustomerAttachment> attachments) {
        this.mContext = context;
        this.attachments = attachments;
        this.inflater = LayoutInflater.from(context);

        if (mMaxMemory == 0) {
            mMaxMemory = (int) (Runtime.getRuntime().maxMemory());
        }

        if (mBitmapCache == null) {
            mBitmapCache = new LruCache<String, Bitmap>(mMaxMemory / 8) {

                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getByteCount();
                }

                @Override
                protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                    if (evicted && oldValue != null && !oldValue.isRecycled()) {
                        oldValue.recycle();
                    }
                }
            };
        }

        if (sectionToPosition != null) {
            sectionToPosition.clear();
        }
    }

    @Override
    public int getCount() {
        return attachments.size();
    }

    @Override
    public Object getItem(int position) {
        return attachments.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (wrParent == null) {
            wrParent = new WeakReference<>((ListView) parent);
        }
        EntityCustomerAttachment item = (EntityCustomerAttachment) getItem(position);

        ViewHolder viewHolder;
        if (null == convertView) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.view_customer_item_attachment, parent, false);
            viewHolder.tv_sort_key_time = (TextView) convertView.findViewById(R.id.tv_sort_key_time);
            viewHolder.iv_avatar_outter = (ImageView) convertView.findViewById(R.id.iv_avatar_outter);
            viewHolder.iv_avatar_inner = (ImageView) convertView.findViewById(R.id.iv_avatar_inner);
            viewHolder.tv_file_name = (TextView) convertView.findViewById(R.id.tv_file_name);
            viewHolder.tv_file_size = (TextView) convertView.findViewById(R.id.tv_file_size);
            viewHolder.fl_menu = (FrameLayout) convertView.findViewById(R.id.fl_menu);
            viewHolder.rl_main_content = (RelativeLayout) convertView.findViewById(R.id.rl_main_content);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        mFile = CustomerUtil.convertAttachmentToEbtFile(item);
        viewHolder.update(mFile);
        viewHolder.setOptionSwitchListener(this, item);
        viewHolder.setOnMultipleSelectListener(this, position);
        return convertView;
    }


    class ViewHolder {

        public TextView tv_sort_key_time;//顶部的title，显示所属的时间
        public ImageView iv_avatar_outter;//左侧显示图像
        public ImageView iv_avatar_inner;//左侧显示图像
        public TextView tv_file_name;//文件名称
        public TextView tv_file_size;//文件大小
        public FrameLayout fl_menu;//右侧菜单键
        public RelativeLayout rl_main_content;//长按后的背景改变

        public void setOptionSwitchListener(View.OnClickListener onClickListener, EntityCustomerAttachment item) {
            fl_menu.setOnClickListener(onClickListener);
            fl_menu.setTag(item);
        }

        public void setOnMultipleSelectListener(View.OnClickListener onClickListener, int position) {
            rl_main_content.setOnClickListener(onClickListener);
            rl_main_content.setTag(position);
        }

        public void update(EbtFile file) {
            tv_file_name.setText(file.name);
            if (file.size > 0) {
                tv_file_size.setText(FileSizeUtil.formetFileSize(file.size));
            } else {
                tv_file_size.setText(FileSizeUtil.getAutoFileOrFilesSize(file.path));
            }
            if (!TextUtils.isEmpty(file.path)) {
                new RepositoryProvider(mContext).setThumbnailImage(iv_avatar_outter, iv_avatar_inner, file);
            } else {
                iv_avatar_inner.setBackgroundColor(0xff2f93e8);
                iv_avatar_inner.setImageResource(R.drawable.empty_pic);
                iv_avatar_outter.setBackgroundColor(0xff2f93e8);
                iv_avatar_outter.setImageResource(R.drawable.empty_pic);
            }
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.fl_menu:
                EntityCustomerAttachment attachment = (EntityCustomerAttachment) v.getTag();
                if (attachment != null) {
//                    popupOptionDialogForAttachment(attachment);
                    showOperationDialog(attachment);
                }
                break;
            case R.id.rl_main_content:
                int position = (Integer) v.getTag();
                if (inMultiMode) {
                    if (contextRecord.isPositionSelected(position)) {
                        //updateview
                        updateItemView(position, false);
                        contextRecord.removeSelectedPosition(position);
                    } else {
                        //updateview
                        updateItemView(position, true);
                        contextRecord.addSelectedPosition(position);
                    }
                } else {
                    File f = new File(AttachmentUtil.netPathToLocalPath(attachments.get(position).path, CustomerConstant.Attachment.DIR_PATH + File.separator));
                    if (f.exists()) {
                        openFile(attachments.get(position));
                    } else {
                        showOperationDialog(attachments.get(position));
                    }
                }
                break;
        }
    }

    private void showOperationDialog(EntityCustomerAttachment attachment) {
        Dialog4CustomerAttachmentOperate dialog4CustomerAttachment = Dialog4CustomerAttachmentOperate.netInstance(attachment);
        ActivityCustomerAll activityCustomerAll = (ActivityCustomerAll) mContext;
        if (activityCustomerAll != null) {
            dialog4CustomerAttachment.show(activityCustomerAll.getSupportFragmentManager(), "Dialog4CustomerAttachmentOperate");
        }
    }


    private void openFile(EntityCustomerAttachment file) {
        openFile(new File(AttachmentUtil.netPathToLocalPath(file.path, CustomerConstant.Attachment.DIR_PATH + File.separator)));
    }

    private void openFile(File file) {
        if (!file.exists()) {
            Toast.makeText(mContext, "文件不存在，请先下载", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            FileUtils.openFile(mContext, file);
        } catch (Exception e) {
            UIHelper.makeToast(mContext,"无法打开此文件格式");
            e.printStackTrace();
        }
    }


    private boolean inMultiMode = false;
    private IMultiSelectRecord contextRecord;
    private View pressedLinearLayout;

    private void updateItemView(int position, boolean selected) {
        ListView listView = wrParent.get();
        //这种情况不可能发生
        if (position < listView.getFirstVisiblePosition() || position > listView.getLastVisiblePosition()) {

        } else {
            //不使用notifyChanged函数
            View item = listView.getChildAt((position - listView.getFirstVisiblePosition()));
            pressedLinearLayout = item.findViewById(R.id.rl_main_content);
            if (selected) {
                pressedLinearLayout.setBackgroundResource(R.drawable.bg_trans_rect_hollow);
            } else {
                pressedLinearLayout.setBackgroundResource(R.drawable.bg_trans_rect_hollow);
            }
        }
    }

    private void updateItemViews() {
        ListView listView = wrParent.get();
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        int lastVisiblePosition = listView.getLastVisiblePosition();

        for (int position = firstVisiblePosition; position <= lastVisiblePosition; position++) {

            View item = listView.getChildAt(position - firstVisiblePosition);
            pressedLinearLayout = item.findViewById(R.id.rl_main_content);

            if (contextRecord.isPositionSelected(position)) {
                pressedLinearLayout.setBackgroundResource(R.drawable.bg_trans_rect_hollow);
            } else {
                pressedLinearLayout.setBackgroundResource(R.drawable.bg_trans_rect_hollow);
            }
        }
    }

    @Override
    public void setMultiSelectMode(boolean inMultiMode) {
        this.inMultiMode = inMultiMode;
        refreshView(inMultiMode);
    }

    @Override
    public boolean getMultiSelectMode() {
        return this.inMultiMode;
    }

    public void refreshView(boolean inMultiMode) {
        if (!inMultiMode) {
            contextRecord.clearSelectedPositions();
        }
        updateItemViews();
    }

    @Override
    public void setMultiSelectRecord(IMultiSelectRecord recorder) {
        contextRecord = recorder;
    }

    @Override
    public void removeDataAtPositions(List positions) {

        List<EntityCustomerAttachment> newAttachments = new ArrayList<EntityCustomerAttachment>();
        Collections.sort(positions);
        int oldSize = attachments.size();
        int posSize = positions.size();
        int posIndex = 0;
        int oldIndex = 0;

        for (; posIndex < posSize; ) {
            for (; oldIndex < oldSize; ) {
                int position = (Integer) positions.get(posIndex);
                if (position == oldIndex) {
                    posIndex++;
                    oldIndex++;
                } else if (position > oldIndex) {
                    newAttachments.add(attachments.get(oldIndex));
                    oldIndex++;
                }
                if (posIndex >= posSize) {
                    for (int i = oldIndex; i < oldSize; i++) {
                        newAttachments.add(attachments.get(i));
                    }
                    break;
                }
            }
        }

        attachments.clear();
        attachments.addAll(newAttachments);
        this.notifyDataSetChanged();
        setMultiSelectMode(false);
    }
}
